
package todolist.util;

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.*;

/*
 * Reference: http://www.code2learn.com/2011/06/encryption-and-decryption-of-data-using.html
 */

/**
 * For encrypting/decrypting data. Singleton.
 * Currently, only todolist.util.Email depends on this class for decryption.
 * Encryption currently unused.
 * @author YouLi
 */
public class Encryption {
	
	// handle singleton instance

	private static Encryption _objEncryption;
	
	public static Encryption getInstance() {
		if (_objEncryption == null)
			_objEncryption = new Encryption();
		return _objEncryption;
	}
	
	// member attributes
	private Key _objKey;

	private static final String _strAlgo = "AES";
	private static final byte[] _bytKeyValue = new byte[] { 'N', 'u', 'S', 'S',
			'T', '1', '2', '0', '1', '2', 'C', 's', '2', '1', '0', '3' };

	private Encryption() {
		_objKey = new SecretKeySpec(_bytKeyValue, _strAlgo);
	}
	
	// facilitators

	/**
	 * Encrypts a non-null String, returns a String of ciphertext.
	 * Returns null if error.
	 */
	public String encrypt(String pstrData) {
		if (pstrData == null)
			return null;
		try {
			Cipher objCipher = Cipher.getInstance(_strAlgo);
			objCipher.init(Cipher.ENCRYPT_MODE, _objKey);
			byte[] bytEncryptedValue = objCipher.doFinal(pstrData.getBytes());
			String strEncryptedValue = new BASE64Encoder().encode(bytEncryptedValue);
			return strEncryptedValue;
		} catch (Exception objEx) {
			return null;
		}
	}

	/**
	 * Decrypts a non-null String of ciphertext, returns a String of plaintext.
	 * Returns null if error.
	 */
	public String decrypt(String pstrData) {
		if (pstrData == null)
			return null;
		try {
			Cipher objCipher = Cipher.getInstance(_strAlgo);
			objCipher.init(Cipher.DECRYPT_MODE, _objKey);
			byte[] bytDecryptedValue = new BASE64Decoder().decodeBuffer(pstrData);
			byte[] bytDecValue = objCipher.doFinal(bytDecryptedValue);
			String strDecryptedValue = new String(bytDecValue);
			return strDecryptedValue;
		} catch (Exception objEx) {
			return null;
		}
	}
	
}
